package com.atguigu.pojo;

import java.util.concurrent.locks.ReentrantLock;

public class TicketLock {
    //定义票数
    private int num = 50;

    //定义可重入锁
    //ReentrantLock还可以实现公平锁，公平锁不允许插队
    public final ReentrantLock lock = new ReentrantLock(true);

    //定义判断当前是否还有票的方法
    public boolean determine(){
        if(num<=0){
            return false;
        }else{
            return true;
        }
    }

    //定义卖票的方法
    //使用synchronized锁解决争抢资源的问题
    public void sale(){
        lock.lock();
        if(!determine()){
            System.out.println(Thread.currentThread().getName()+ "票已卖完");
            lock.unlock();
            return;
        }
        try {
            System.out.println(Thread.currentThread().getName()+"开始卖票，当前票数："+ num-- +",剩余票数："+num);
            check();
            Thread.sleep(50);
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        } finally {
            lock.unlock();
        }
    }

    //测试可重入锁
    public void check(){
        lock.lock();
        System.out.println("等待卖票……");
        lock.unlock();
    }
}
